//
//  FKChargeTypeVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/28.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKChargeTypeVC.h"
#import "FKPayMethodCell.h"
#import "FKChargeResultVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h> // 微信支付

@interface FKChargeTypeVC ()

@property (nonatomic, weak) UILabel *priceLabel;
@property (nonatomic, strong) NSArray *datas;

@end

@implementation FKChargeTypeVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = @[@{@"title" : @"微信支付", @"icon" : @"fk_payment_wechat", @"type" : @"wechat"},
                   @{@"title" : @"支付宝支付", @"icon" : @"fk_payment_alipay", @"type" : @"alipay"}];
    }
    return _datas;
}

- (instancetype)initWithStyle:(UITableViewStyle)style
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付方式";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivePayResult:) name:@"wechatPay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivePayResult:) name:@"alipay" object:nil];
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(50))];
    header.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [UILabel fk_labelWithFont:fk_adjustFont(15) textColor:fkColor333333 text:@"订单金额"];
    [header addSubview:titleLabel];
    
    UILabel *priceLabel = [UILabel fk_labelWithFont:fk_adjustFont(16) textColor:fkMainColor];
    [header addSubview:priceLabel];
    self.priceLabel = priceLabel;
    self.tableView.tableHeaderView = header;
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, 88)];
    
    UIButton *confirmBtn = [UIButton fk_btnWithTarget:self action:@selector(confirmBtnClicked) font:fk_adjustFont(17) normalTitle:@"确认支付" normalTitleColor:[UIColor whiteColor] selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage imageNamed:@"bg_main"] selectedBgImg:nil];
    [footer addSubview:confirmBtn];
    [confirmBtn fk_viewCornerRadius:5 borderWidth:0 borderColor:nil];
    
    self.tableView.tableFooterView = footer;
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.centerY.offset(0);
    }];
    [priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-12);
        make.centerY.offset(0);
        make.left.greaterThanOrEqualTo(titleLabel.mas_right).offset(8);
    }];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.right.offset(-15);
        make.height.offset(fk_adjustW(44));
        make.bottom.offset(0);
    }];
    priceLabel.text = fkFORMAT(@"￥%@", self.data[@"markprice"]);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:false scrollPosition:UITableViewScrollPositionNone];
        [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    });
    self.tableView.contentInset = UIEdgeInsetsMake(fk_adjustW(10), 0, 0, 0);
}

- (void)receivePayResult:(NSNotification *)noti
{
    NSDictionary *dict = noti.userInfo;
    BOOL success = [dict[@"success"] boolValue];
   
    FKChargeResultVC *vc = [[FKChargeResultVC alloc] init];
    vc.needRemoveBeforeVc = true;
    vc.failure = !success;
    fkPushNav(vc);
}

- (void)confirmBtnClicked
{
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    if (!indexPath) {
        [SVProgressHUD showInfoWithStatus:@"请选择充值方式"];
        return;
    }
    __block NSDictionary *data = self.datas[indexPath.row];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"payment"] = data[@"type"];
    param[@"recharge_id"] = self.data[@"id"];
    param[@"trade_type"] = @"APP";
    [FKHttpTool postWithSuffix:@"m=Home&c=Payment&a=recharge" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if ([data[@"type"] isEqualToString:@"wechat"]) {
                PayReq *req = [[PayReq alloc] init];
                req.partnerId = result.data[@"partnerid"];
                req.prepayId = result.data[@"prepayid"];
                req.nonceStr = result.data[@"noncestr"];
                req.timeStamp = [result.data[@"timestamp"] intValue];
                req.package = result.data[@"package"];
                req.sign = result.data[@"sign"];
                [WXApi sendReq:req];
            } else if ([data[@"type"] isEqualToString:@"alipay"]) {
                NSString *str = result.data[@"paystr"];
                // NOTE: 调用支付结果开始支付
                NSString *scheme = [NSBundle mainBundle].bundleIdentifier; // 我自己直接用bundleID作为scheme了
                [[AlipaySDK defaultService] payOrder:str fromScheme:scheme callback:nil];
            }
        } else {
            FKChargeResultVC *vc = [[FKChargeResultVC alloc] init];
            vc.needRemoveBeforeVc = true;
            vc.failure = true;
            fkPushNav(vc);
        }
    } failure:nil];
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKPayMethodCell *cell = [FKPayMethodCell cellWith:tableView];
    cell.model = self.datas[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return fk_adjustW(40);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    if (!header) {
        header = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"header"];
        
        UILabel *titleLabel = [UILabel fk_labelWithFont:fk_adjustFont(13) textColor:fkColor999999 text:@"支付方式"];
        [header.contentView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.centerY.offset(0);
        }];
    }
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end
